<?php
/**
 * XGPHP 轻量级PHP框架
 * @link http://xgphp.xg3.cn
 * @version 2.0.0
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @author 讯高科技 <xungaokeji@qq.com>
*/
namespace xg;

class Command {
    protected $arguments = [];
    public function __construct($argv) {
        array_shift($argv); // Remove the script name
        $this->parseArguments($argv);
    }
    private function parseArguments($argv) {
        foreach ($argv as $arg) {
            if (strpos($arg, '--') === 0) {
                $eqPos = strpos($arg, '=');
                if ($eqPos !== false) {
                    $key = substr($arg, 2, $eqPos - 2);
                    $value = substr($arg, $eqPos + 1);
                } else {
                    $key = substr($arg, 2);
                    $value = true;
                }
                $this->arguments[$key] = $value;
            } elseif (strpos($arg, '-') === 0) {
                $key = substr($arg, 1);
                $value = true;
                $this->arguments[$key] = $value;
            } else {
                $this->arguments[] = $arg;
            }
        }
    }

    public function getArgument($key, $default = null) {
        return isset($this->arguments[$key]) ? $this->arguments[$key] : $default;
    }

    public function getArguments() {
        return $this->arguments;
    }

    public function run() {
        $command = $this->getArgument(0);
        if (!$command) {
            echo "No command specified.\n";
            return;
        }

        $method = $command . 'Command';
        if (method_exists($this, $method)) {
            call_user_func([$this, $method]);
        } else {
            echo "Command '$command' not found.\n";
        }
    }
}
?>